package cn.seocoo.platform.api.util;

import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/api/WeiXin")
public class GetWXUnionid {
    @Value("${wechat.appId}")
    private String wechatAppId;
    @Value("${wechat.secretKey}")
    private String wechatSecretKey;
    @Value("${wechat.session.grantType}")
    private String grantType;
    /**
     * 获取微信unionid
     * @author pyh
     * @param code
     * @return
     */
    @GetMapping("/GetWXUnionid")
    @ApiOperation("用户登录")
    @ResponseBody
    private String GetWXUnionid(String code) {
        String unionid = "";
        if (code == null || code.length() == 0) {
            return unionid;
        }
        //微信的接口
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + "wx60ae7517f6672160" +
                "&secret=" + "c20544a7f9d2e218a35e9c54bc324351" + "&js_code=" + code + "&grant_type=" + "authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
            //System.out.println("responseEntity:"+responseEntity);
            String sessionData = responseEntity.getBody();
            JSONObject json = JSONObject.fromObject(sessionData);
            // getting session_key
            //String sessionKey = json.get("session_key").toString();
            // getting open_id
//            unionid = json.get("unionid").toString();
//            return unionid;
            return json.toString();
        }
        return unionid;
    }
}
